/*
 * @Author: 肖思汗 
 * @Date: 2020-08-25 00:33:47 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-03-28 16:51:51
 */

import cuid from "cuid";
import events from 'events';

const emitter = new events();

export default class mixin_emitter {

    constructor() {

    }

    id = cuid();

    // 全局的事件监听对象
    emitter = emitter;

    // 记录的此对象上上的 事件名和 回调
    callbacks: Array<{ eventName: string, callback: (...args: any[]) => void }> = [];

    // 分发事件
    emit(eventName: string, ...arg: any) {
        this.emitter.emit(eventName, arg);
    }

    // 添加监听
    on(eventName: string, callback: (...args: any[]) => void) {

        // 先取消一次避免重复监听
        this.emitter.off(eventName, callback);
        // 添加监听事件
        this.emitter.on(eventName, callback);

        // 记录监听事件方便组件卸载时取消
        this.callbacks.push({ eventName, callback });
    }

    // 添加一次性的监听
    once(eventName: string, callback: (...args: any[]) => void) {
        // 添加监听事件
        this.emitter.on(eventName, callback);
        this.callbacks.push({ eventName, callback });
    }

    // 取消监听
    off(eventName: string, callback: (...args: any[]) => void) {
        this.emitter.off(eventName, callback);
    }

    // 移除此对象上记录的所有监听
    removeAll() {
        this.callbacks.map(call => {
            this.emitter.off(call.eventName, call.callback);
        });
    }

    // 事件常量
    HELLO_WORLD = 'hello world'
}